<template>
  <el-dialog
    append-to-body
    fullscreen
    :title="title"
    :visible.sync="dialogVisible"
    width="1600px"
    @close="close"
  >
    <template slot="title">
      <div>
        <span class="font16 mr12">{{ title }}</span>
        <el-button
          v-if="bloods.length > 0"
          class="ml12"
          icon="el-icon-document"
          type="primary"
          @click="handleSubmit"
        >
          提交
        </el-button>
      </div>
    </template>
    <vxe-grid v-bind="gridOptions" align="center" :data="bloods">
      <template #id_out="{ row, $index }">
        <el-input
          :ref="`input${$index * 4 + 1}`"
          v-model="row.id_out"
          class="wd150"
          clearable
          :placeholder="`input${$index * 4 + 2}`"
          size="mini"
          @input="handleChange(row, `input${$index * 4 + 2}`, $index)"
        />
      </template>
      <template #abo_code="{ row, $index }">
        <el-input
          :ref="`input${$index * 4 + 2}`"
          v-model.trim="row.abo_code"
          clearable
          placeholder="血型码"
          size="mini"
          @input="
            parseBloodGroupRhdByCode(row, `input${$index * 4 + 3}`, $index)
          "
        />
      </template>
      <template #product_code="{ row, $index }">
        <el-input
          :ref="`input${$index * 4 + 3}`"
          v-model.trim="row.product_code"
          clearable
          placeholder="血液成分码"
          size="mini"
          @input="
            parseBloodComponentByCode(row, `input${$index * 4 + 4}`, $index)
          "
        />
      </template>
      <template #invalid_time_code="{ row, $index }">
        <el-input
          :ref="`input${$index * 4 + 4}`"
          v-model.trim="row.invalid_time_code"
          clearable
          placeholder="失效日期码"
          size="mini"
          @input="
            parseBloodInvalidTimeByCode(row, `input${$index * 4 + 5}`, $index)
          "
        />
      </template>
      <template #product="{ row }">
        <el-cascader
          v-model="row.product_id_path"
          clearable
          filterable
          :options="products"
          :props="props"
          :show-all-levels="false"
        />
      </template>
      <template #abo="{ row }">
        <el-select
          v-model="row.abo"
          clearable
          filterable
          placeholder="血型"
          size="mini"
        >
          <el-option
            v-for="(item, index) in bloodGroups"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </template>
      <template #rhd="{ row }">
        <el-select
          v-model="row.rhd"
          clearable
          filterable
          placeholder="Rh(D)"
          size="mini"
        >
          <el-option
            v-for="(item, index) in bloodRhds"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </template>
      <template #capacity="{ row }">
        <el-input-number
          v-model="row.capacity"
          controls-position="right"
          :min="0.5"
          placeholder="血量"
          size="mini"
        />
      </template>
      <template #collect_time="{ row }">
        <el-date-picker
          v-model="row.collect_time"
          align="center"
          class="wd150"
          placeholder="选择日期时间"
          size="mini"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </template>
      <template #invalid_time="{ row }">
        <el-date-picker
          v-model="row.invalid_time"
          align="center"
          placeholder="选择日期时间"
          size="mini"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </template>
      <template #blood_user="{ row }">
        <el-input
          v-model="row.blood_user"
          clearable
          placeholder="捐血者"
          size="mini"
        />
      </template>
      <template #operate-header>
        <el-link icon="el-icon-plus" type="primary" @click="handleAdd">
          增加
        </el-link>
      </template>
      <template #operate="{ $index }">
        <el-link
          icon="el-icon-delete"
          type="danger"
          @click="handleDelete($index)"
        >
          删除
        </el-link>
      </template>
    </vxe-grid>
  </el-dialog>
</template>

<script>
  import {
    getNextTime,
    parseBloodGroupRhdByCode,
    parseBloodComponentByCode,
    parseBloodInvalidTimeByCode,
    padEnd,
  } from '@/utils'
  import {
    bloodSerialnoLength,
    bloodFullSerialnoLength,
    bloodGroupRhdCodelength,
    bloodComponentCodeLength,
    bloodInvalidTimeCodeLength,
  } from '@/utils/constant'
  import { mapGetters } from 'vuex'
  export default {
    data() {
      return {
        dialogVisible: false,
        bloodSerialnoLength,
        title: '外买血液接收',
        bloods: [],
        bloodGroups: ['A', 'B', 'AB', 'O'],
        bloodRhds: ['阳性', '阴性'],
        props: { label: 'name', value: 'id' },
        gridOptions: {
          border: true,
          height: '600px',
          resizable: true,
          size: 'small',
          stripe: true,
          keepSource: true,
          columns: [
            {
              title: '操作',
              field: 'act',
              width: 80,
              fixed: 'left',
              slots: { default: 'operate', header: 'operate-header' },
            },
            { title: '编号', field: 'idx', type: 'seq', width: 80 },
            {
              title: '原始血袋号',
              field: 'id_out',
              showOverflow: true,
              sortable: true,
              slots: { default: 'id_out' },
            },
            {
              title: '血型码',
              field: 'abo_code',
              showOverflow: true,
              sortable: true,
              slots: { default: 'abo_code' },
            },
            {
              title: '血液成分码',
              field: 'product_code',
              showOverflow: true,
              sortable: true,
              slots: { default: 'product_code' },
            },
            {
              title: '失效日期码',
              field: 'invalid_time_code',
              showOverflow: true,
              sortable: true,
              slots: { default: 'invalid_time_code' },
            },
            {
              title: '血液成分',
              field: 'product',
              showOverflow: true,
              sortable: true,
              slots: { default: 'product' },
            },
            {
              title: '血型',
              field: 'abo',
              showOverflow: true,
              sortable: true,
              slots: { default: 'abo' },
            },
            {
              title: 'Rh(D)',
              field: 'rhd',
              showOverflow: true,
              sortable: true,
              slots: { default: 'rhd' },
            },
            {
              title: '血量',
              field: 'capacity',
              showOverflow: true,
              sortable: true,
              slots: { default: 'capacity' },
            },
            {
              title: '采血时间',
              field: 'collect_time',
              showOverflow: true,
              sortable: true,
              slots: { default: 'collect_time' },
            },
            {
              title: '失效时间',
              field: 'invalid_time',
              showOverflow: true,
              sortable: true,
              slots: { default: 'invalid_time' },
            },
            {
              title: '捐血者',
              field: 'blood_user',
              showOverflow: true,
              sortable: true,
              slots: { default: 'blood_user' },
            },
          ],
        },
      }
    },
    computed: {
      ...mapGetters(['products']),
    },
    mounted() {
      this.enterKeyup()
      this.$nextTick(() => {
        if (this.$refs.input1) {
          this.$refs.input1.focus()
        }
      })
    },
    methods: {
      show() {
        this.dialogVisible = true
      },
      close() {
        this.bloods = [
          {
            id_out: '',
            product_id_path: '',
            abo: '',
            rhd: '阳性',
            capacity: 1,
            collect_time: '',
            invalid_time: '',
            blood_user: '',
            abo_code: '',
            product_code: '',
            invalid_time_code: '',
          },
        ]
        this.dialogVisible = false
      },
      handleAdd() {
        this.bloods.push({
          id_out: '',
          product_id_path: '',
          abo: '',
          rhd: '阳性',
          capacity: 1,
          collect_time: '',
          invalid_time: '',
          blood_user: '',
          abo_code: '',
          product_code: '',
          invalid_time_code: '',
        })
      },
      handleDelete(index) {
        this.bloods.splice(index, 1)
      },
      handleSubmit() {
        this.$emit('submit', this.bloods)
      },
      switchTab(ref, index) {
        this.currentIndex = index
        if (this.$refs[ref]) {
          this.$refs[ref].focus()
        }
      },
      parseBloodGroupRhdByCode(row, ref, index) {
        let abo_code = row.abo_code || ''
        const pattern = /\w+/
        const result = abo_code.match(pattern)
        if (result) {
          abo_code = result[0]
          row.abo_code = abo_code
          if (abo_code.length === bloodGroupRhdCodelength) {
            console.log(ref, index)
            const blood = parseBloodGroupRhdByCode(abo_code)
            row.blood_group = blood.blood_group
            row.blood_rhd = blood.blood_rhd
            setTimeout(() => {
              this.switchTab(ref, index)
            }, 300)
          }
        }
      },
      parseBloodComponentByCode(row, ref, index) {
        let product_code = row.product_code || ''
        const pattern = /\w+/
        const result = product_code.match(pattern)
        if (result) {
          product_code = result[0]
          row.product_code = product_code
          const res = parseBloodComponentByCode(
            product_code,
            this.bloodComponentsFilter
          )
          if (
            res.length === 2 &&
            product_code.length === bloodComponentCodeLength
          ) {
            row.blood_component_id_path = res
            row.blood_component_id = res[1]
            setTimeout(() => {
              this.switchTab(ref, index)
            }, 300)
          } else {
            row.blood_component_id_path = ''
            row.blood_component_id = ''
          }
        }
      },
      parseBloodInvalidTimeByCode(row, ref, index) {
        let invalid_time_code = row.invalid_time_code || ''
        const pattern = /\w+/
        const result = invalid_time_code.match(pattern)
        if (result) {
          invalid_time_code = result[0]
          row.invalid_time_code = invalid_time_code
          const res = parseBloodInvalidTimeByCode(invalid_time_code)
          console.log(res)
          row.blood_invalid_time = res
          if (
            row.blood_component_id_path &&
            row.blood_component_id_path.length > 0 &&
            invalid_time_code.length === bloodInvalidTimeCodeLength
          ) {
            const valid_days = this.getValidDays(row)
            row.blood_collect_time = getNextTime(res, valid_days * -1)
            setTimeout(() => {
              this.switchTab(ref, index)
            }, 300)
          }
        }
      },
      selectInvalidTime(row) {
        const valid_days = this.getValidDays(row)
        row.blood_collect_time = getNextTime(
          row.blood_invalid_time,
          valid_days * -1
        )
      },
      handleChange(row, ref, index) {
        console.log(row, ref, index)
        if (row.blood_serialno.length >= this.bloodSerialnoLength - 1) {
          const timeout =
            row.blood_serialno.length >= bloodFullSerialnoLength - 1
              ? this.bloodTimoutS
              : this.bloodTimoutL
          setTimeout(() => {
            row.blood_serialno = padEnd(
              row.blood_serialno,
              bloodFullSerialnoLength,
              0
            )
            if (row.blood_serialno.length >= this.bloodFullSerialnoLength) {
              row.blood_user = row.blood_serialno.substr(4, 9)
              this.switchTab(ref, index)
            }
          }, timeout)
        }
      },
      selectBloodComponent(row) {
        const valid_days = this.getValidDays(row)
        row.blood_collect_time = getNextTime(
          row.blood_invalid_time,
          valid_days * -1
        )
        row.blood_component_id = row.blood_component_id_path[1]
      },
      getValidDays(row) {
        let valid_days = 30
        if (row.blood_component_id_path) {
          const blood_component =
            this.bloodComponentsAllObj[row.blood_component_id_path[1]]
          valid_days = blood_component.valid_days
        }
        return valid_days
      },
      getMaxCapacity(row) {
        let max = 2
        if (row.blood_component_id_path) {
          const blood_component =
            this.bloodComponentsAllObj[row.blood_component_id_path[1]]
          max = +blood_component.max || 2
        }
        return max
      },
      tableRowClassName({ row, rowIndex }) {
        row.index = rowIndex
      },
      setIndex(row) {
        this.currentIndex = row.index
      },
      enterKeyup() {
        document.addEventListener('keyup', this.enterKey)
      },
      enterKey(event) {
        const code = event.keyCode
          ? event.keyCode
          : event.which
          ? event.which
          : event.charCode

        if (code === 13) {
          const index = this.currentIndex + 1
          this.currentIndex = index
          const ref = `input${4 * index + 1}`
          if (this.$refs[ref]) {
            this.$refs[ref].focus()
          }
        }
      },
    },
  }
</script>

<style lang="scss" scoped></style>
